import { ref, watch, computed, inject } from 'vue'
import { useBuildAttrsKeys, AConfigProviderTypes } from '@/components'

export const useHttpData = (props: any, finallyFun: () => void) => {
  const data = ref<any[]>([])

  const params = computed(() => {
    return {
      ...props.params,
      ...props.pageConfig
    }
  })

  const attrs = inject<AConfigProviderTypes>(useBuildAttrsKeys)
  const { CETable } = attrs as any
  const { transform } = CETable

  const getHttpData = async () => {
    const http = props.http
    if (http && typeof http === 'function') {
      const res = await http(params.value)
      const _data = transform({ data: res.records, total: res.total })
      data.value = _data.data || []
      finallyFun()
    } else {
      data.value = props.data || []
    }
  }

  watch(
    () => props.params,
    () => {
      // 是否懒加载~~
      if (props.isLazy) {
        return
      }
      getHttpData()
    },
    {
      immediate: true
    }
  )

  watch(
    () => props.isReload,
    () => {
      if (props.isReload) {
        getHttpData()
      }
    }
  )
  return {
    data
  }
}
